package com.inxedu.os.edu.service.student.impl;

import com.inxedu.os.edu.dao.EduUserMapper;
import com.inxedu.os.edu.pojo.EduUser;
import com.inxedu.os.edu.pojo.EduUserExample;
import com.inxedu.os.edu.pojo.EduUserLoginLog;
import com.inxedu.os.edu.pojo.QueryUser;
import com.inxedu.os.edu.service.student.StudentService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private EduUserMapper eduUserMapper;

    @Override
    public List<EduUser> findAllByUser() {
        EduUserExample EduUserExample=new EduUserExample();
        return eduUserMapper.selectByExample(EduUserExample);
    }

    @Override
    public List<EduUser> findByUserMh(@Param("record") QueryUser record) {
        return eduUserMapper.findByUserListMh(record);
    }

    @Override
    public void updateUserPwd(EduUser eduUser) {

        eduUserMapper.updateUserPwd(eduUser);
    }

    @Override
    public void updateByUserState(EduUser eduUser) {

        eduUserMapper.updateByUserState(eduUser);
    }

    @Override
    public int findByUserId(int userId) {

        return eduUserMapper.findUserById(userId);
    }

    @Override
    public List<EduUserLoginLog> findUserLogPage(int userId) {//, PageEntity page
        return eduUserMapper.findUserLogPage(userId);
    }

    /**
     * 批量开通学员账号
     * @param request
     * @param myFile
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public String AddImportExcel(HttpServletRequest request, MultipartFile myFile) throws Exception {//, Integer mark

            String msg="";
            //HSSFWorkbook:是操作Excel2003以前（包括2003）的版本，扩展名是.xls
            //XSSFWorkbook:是操作Excel2007后的版本，扩展名是.xlsx；
            //SXSSFWorkbook:是操作Excel2007后的版本，扩展名是.xlsx；
            HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream());
            //获取一个工作表
            HSSFSheet sheet = wookbook.getSheet("Sheet1");

            int rows =sheet.getLastRowNum();//获取共有多少行数据

            if(rows==0){
                throw new Exception("请填写数据");
            }

            for (int i = 1; i <= rows+1; i++) {
                // 读取左上端单元格
                HSSFRow row = sheet.getRow(i);
                // 行不为空
                if (row != null) {
                    // **读取cell**
                    String email = getCellValue(row.getCell((short) 0));//邮箱
                    String mobile = getCellValue(row.getCell((short) 1));//手机
                    String pwd = getCellValue(row.getCell((short) 2));//获得密码

                    //邮箱
                    if (email.equals("")) {
//                        if (mark == 1) {
                            msg += "第" + i + "行邮箱错误<br/>";
                            continue;
//                        } else {
//                            throw new Exception("第" + i + "行邮箱错误<br/>");
//                        }
                    }

                    boolean b = checkEmail(email.toLowerCase());
                    if (b == true) {
//                        if (mark == 1) {
                            msg += "第" + i + "行邮箱已存在<br/>";
                            continue;
//                        } else {
//                            throw new Exception("第" + i + "行邮箱已存在<br/>");
//                        }
                    }
                    //手机
                    if (mobile == null || mobile.equals("")) {
//                        if (mark == 1) {
                            msg += "第" + i + "行手机错误<br/>";
                            continue;
//                        } else {
//                            throw new Exception("第" + i + "行手机错误<br/>");
//                        }
                    }

                    //密码
                    if (pwd == null && !pwd.equals("")) {
                        if (pwd.length() < 6 || pwd.length() > 20) {
//                            if (mark == 1) {
                                msg += "第" + i + "行密码错误<br/>";
                                continue;
//                            } else {
//                                throw new Exception("第" + i + "行密码错误<br/>");
//                            }
                        }
                    }
                    if (pwd == null || pwd.equals("")) {
                        pwd = "111111";
                    }
                     EduUser user = new EduUser();
                    user.setEmail(email);//用户学员邮箱
                    user.setMobile(mobile);//用户学员手机
                    user.setPassword(pwd);//用户学员密码
                    user.setCreateTime(new Date());//注册时间
                    user.setLastSystemTime(new Date());//上传统计系统消息时间
                    user.setIsAvalible((byte)1);//添加状态
                    user.setAge((byte)0);
                    user.setSex((byte)0);
                    eduUserMapper.insert(user);//执行添加sql语句
                }
            }return msg;

    }

    /**
     * 获取Hsscell内容
     *
     * @param cell
     * @return
     */
    public String getCellValue(HSSFCell cell) {
        String value = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_FORMULA:
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    DecimalFormat df = new DecimalFormat("0");
                    value = df.format(cell.getNumericCellValue());
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    value = cell.getStringCellValue().trim();
                    break;
                default:
                    value = "";
                    break;
            }
        }
        return value.trim();
    }

    /**
     * 判断邮箱是否存在
     * @param email
     * @return
     */
    public boolean checkEmail(String email) {
        int count = eduUserMapper.checkEmail(email);
        if(count>0){
            return true;
        }
        return false;
    }


    //查找所有学员
    @Override
    public List<EduUser> FindUserAll() {
        EduUserExample example = new EduUserExample();
        return eduUserMapper.selectByExample(example);
    }
}
